<?php 
	require_once("init.php");  
?>

<?php
	if (!isset($_POST["username"]) || !isset($_POST["password"]) || !isset($_POST["email"]) 
			|| strlen($_POST["username"]) < 4 || strlen($_POST["username"]) > 20 
			|| strlen($_POST["password"]) < 4 || strlen($_POST["password"]) > 20 
			|| strlen($_POST["email"]) < 5 || strlen($_POST["email"]) > 100
			|| !isValidEmail($_POST["email"])) {
?>
<div id="register-fail" title="Oops!" class="panel">
	<p>Please make sure that you've entered valid username, password, and email address. The following rules apply:</p>
  <ul class="small">
  	<li>Username must be between 4-20 characters</li>
  	<li>Password must be between 4-20 characters</li>
  	<li>Email address must be in valid format</li>
  </ul>
</div>
<?php
	} else {
		if (!isset($_POST["password2"]) || strlen($_POST["password2"]) < 4 || strlen($_POST["password2"]) > 25 
				|| $_POST["password"] != $_POST["password2"]) {
?>
<div id="register-fail" title="Oops!" class="panel">
	<p>The password that you re-typed is different from the first one. Please try again.</p>
</div>
<?php
		} else {
			// Check if user exists
			$qCheckUser = mysql_query("
				SELECT *
				FROM users 
				WHERE username = '".$_POST["username"]."'
					OR email = '".$_POST["email"]."'
			");
		
			if (mysql_num_rows($qCheckUser) > 0) {
?>
<div id="register-fail" title="Oops!" class="panel">
	<p>An account with your username or email address already exists.</p>
</div>
<?php
			} else {
				// Register new user account
				$qRegisterUser = mysql_query("
					INSERT INTO users (
						username,
						password,
						email,
						dateAdded
					)
					VALUES (
						'".$_POST["username"]."',
						'".$_POST["password"]."',
						'".$_POST["email"]."',
						now()
					)
				");
				$qGetNewUserId = mysql_query("
					SELECT userId
					FROM users 
					WHERE username = '".$_POST["username"]."'
					ORDER BY userId DESC
				");
				$newUserId = mysql_fetch_array($qGetNewUserId);
				$_SESSION["userId"] = $newUserId["userId"];
				$_SESSION["username"] = $_POST["username"];
?>
<form id="registerSuccess" class="dialog" method="post" target="_self" action="redirect.php?url=index.php">
	<fieldset>
    <h1>You are now a member!</h1>
    <p align="center">You have also been signed in. Have fun!</p>
    <p align="center"><input class="submit" type="submit" name="submit" value="Continue" /></p>
  </fieldset>
</form>
<?php
			}
		}
	}
?>

<?php 
	require_once("end.php"); 
?>